<template>
	<div class="vue_app">
		<my-header :title="'线下订单'" :hasTitle="true" :hasBack="true" :goBack="goBack"></my-header>
		<div class="content">
			<!--商品列表-->
			<div class="aui-content choose_list">
				<ul class="aui-list aui-media-list">
					<li class="aui-list-item iscroll_list">
						<div id="co_orderGoods" class="aui-media-list-item-inner scroller_list" v-if="goodsList">
							<div class="aui-list-item-media" v-for="(item,index) in goodsList" :key="index">
								<img :src="item.goodsImg || 'static/image/demo1.png'" style="height: 100%;width: 100%;"/>
								<em style="background:#EF5423;opacity: 0.6;">x{{item.goodsType == 7?'1':item.goodsNum}}</em>
							</div>
						</div>
					</li>
				</ul>
				<div class="aui-list-item-arrow statistics">   <!-- num-->
					<p>共<span id="co_totalPiece" style="padding-top: 0.5rem;">{{num}}</span>件</p>
					<!--<p id="co_totalPackage">1个包裹</p>-->
					<!--<p id="co_totalPackage">常规配送</p>-->
				</div>
			</div>
			 <div style="margin-bottom: 0.75rem;margin-top: -0.75rem;">
			 	<!--v-if="sendNameArr && sendNameArr.length != 0" -->
				<div class="aui-list-item-arrow01 server_show"  v-if="sendNameArr && sendNameArr.length != 0" style="background-color: #fff2f2;padding: 0.2rem 0.5rem;">
			        <div style="margin-left: 15;text-align: left;" class="aui-list-item-arrow_2">
						<h4>[赠品]</h4>
						<dl>
							<dd v-for="(item,index) in sendNameArr" :key="index">   <!--v-for="(item,index) in sendNameArr" -->
								<font>{{item}}</font>   <!--赠品名称  --> 
								<!--<span>¥9.8×1</span>-->
							</dd>
						</dl>
					</div>
				</div>
		    </div>
			<!--商品列表 end-->
			<!--信息列表-->
			<div class="aui-content aui-margin-b-15">
				<ul class="aui-list aui-list-in">
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">商品金额</div>
							<div id="co_totalMoney" class="aui-list-item-right">￥{{goodsTotalMoney}} <span v-if="addMoney">(含加工费：￥{{}})</span></div>
						</div>
					</li>
					<!--<li class="aui-list-item aui-list-item-arrow" v-if="false">
						<div class="aui-list-item-inner" @click="showGiftCard">
							<div class="aui-list-item-title">我的钱包</div>
							<div class="aui-list-item-right" >{{getUseGiftCard?'已选择':''}}</div>
						</div>
					</li>-->
					<li class="aui-list-item aui-list-item-arrow">
						<div class="aui-list-item-inner" @click="showCoupon">
							<div class="aui-list-item-title">优惠券</div>
							<div class="aui-list-item-right"><span style="color: #EF5423;padding-right: 0.1rem;" v-if="getTicketList.length === 0 && couponCount">{{couponCount}}</span>{{ticketList}}</div>
						</div>
					</li>
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">优惠金额</div>
							<div id="co_totalMinis" class="aui-list-item-right">￥{{discountMoney}}</div>
						</div>
					</li>
				</ul>
			</div>
			<!--信息列表 end-->
			<!--<div class="aui-content aui-margin-b-15">
				<ul class="aui-list aui-form-list liuyan">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner" style="align-items:flex-start;">
                        <div class="aui-list-item-label" style="line-height:2rem;">买家留言：</div>
                        <div class="aui-list-item-input">
                            <textarea placeholder="选填：输入留言信息" v-model="myNode" maxlength="100"></textarea>
                        </div>
                    </div>
                </li>
            </ul>
			</div>-->
			<div class="total_sf">
				<h2><span id="co_realpay" >实付金额：￥ {{totalMoney}}</span> <p style="display: inline;" v-if="false">(省：￥ 1.00)</p> </h2>
				<p>如需发票，请到门店索取</p>
			</div>
			<!--立即下单-->
			<div style="height:4rem;"></div>
			<div class="settle_accounts lijixiadan">
				<div class="aui-btn aui-btn-danger aui-btn-block aui-btn-sm" @click.stop="toPay">提交订单</div>
			</div>
			<!--去结算 end-->
		</div>
		<confirm-gift-card ref="giftCard"></confirm-gift-card>
		<confirm-order-pursekey ref="pursekey" :sendOrder="toPay"></confirm-order-pursekey>
		<confirm-coupon ref="coupon" :couponArr="couponArr" :couponArrHtm="couponArrHtm" :couponMoney="couponM" :money="totalMoney" :getCouponMoney="changeCoupon"></confirm-coupon>
	</div>
</template>

<script>
	import axios from 'axios';
	import { MessageBox } from '../../ui-components'
	import { Toast } from '../../utils/toast';
	import { mapGetters, mapActions, mapMutations } from "vuex";
	import MyHeader from "../header";
	import ConfirmCoupon from "../../real-components/ConfirmOrder/ConfirmCoupon";
	import ConfirmOrderPursekey from "../../real-components/ConfirmOrder/ConfirmOrderPursekey";
	import ConfirmGiftCard from "../../real-components/ConfirmOrder/ConfirmGiftCard";
	import {xianxia} from "../../config/orderTypeCode";
	export default {
		props: {
			//         sendOrder:{
			//	           	type:Function,
			//	           	default:()=>{}
			//         },
			//         checkedgoodsList:{
			//         		type:Array,
			//         		default:function(){
			//         			let arr = [];
			//         			return arr
			//         		}
			//         },
			//         normalList:{
			//         		type:Array,
			//         		default:function(){
			//         			let arr = [];
			//         			return arr
			//         		}
			//         },
			//         bigList:{
			//         		type:Array,
			//         		default:function(){
			//         			let arr = [];
			//         			return arr
			//         		}
			//         },
			//         sendMoney:{
			//         		type:Array,
			//         		default:function(){
			//         			let arr = [];
			//         			return arr
			//         		}
			//         },
		},
		components: {
			"my-header": MyHeader,
			"ConfirmCoupon": ConfirmCoupon,
			"confirm-order-pursekey": ConfirmOrderPursekey,
			"ConfirmGiftCard": ConfirmGiftCard
		},
		computed: {
			...mapGetters('wxh', [
				'sessionId',
				'userInfo'
			]),
			...mapGetters('zx', [
				"getTicketList", "getAvailAmount", "getUseGiftCard"
			]),
			ticketList() {
				if(this.getTicketList.length === 0) {
					if(this.couponCount){
						this.couponFlag = "组可用";
					}else{
						this.couponFlag = '';
					}
				} else {
					this.couponFlag = "已选择";
				}
				return this.couponFlag;
			},
			couponM() {
				//				if(Number(this.goodsMoney) - this.couponMoney > 0) {
				//					this.money = Number(this.money) - Number(this.couponMoney);
				//				} else {
				//					this.couponMoney = Number(this.goodsMoney);
				//					this.money = 0;
				//				}
				//				return this.couponMoney;

			},
			totalMoney() {
				return this.goodsPromTotalMoney;
			},
		},
		watch: {

		},
		data() {
			return {
				mynode: '',
				addMoney: '',
				goodsList: [],
				num: 0,
				orderData: null,
				goodsTotalMoney: 0, // 商品金额
				discountMoney: 0, // 优惠的金额
				goodsPromTotalMoney: 0, //实付金额
				couponArr: null, // 优惠券数组
				couponArrHtm: null, // 用于展示的优惠券数组
				couponFlag: '', //是否选择优惠券
				couponMoney: 0, // 优惠券优惠金额
				money: 0, //总金额
				storeOrderNo: null, // 线下订单号
				shopId: 0, // 线下门店
				moneyWithoutC: 0, //钱包免密金额
				keyall: null, // 钱包密码
				showMask: false, //是否需要用戶輸入密碼
				walletStatus: null, // 是否已经设置钱包密码
				sendNameArr:[], // 赠品名称数组  赠优惠券 赠商品
				couponCount:0 , // 可用优惠券组数
				clickFlag:true  // 防止两次快速点击 调用两次下单接口
//				moneyWithoutCode: 0, //免密金额
			}
		},
		methods: {
			...mapMutations('zx', [
				"setUseGiftCard"
			]),
			initData() {
			
				if(this.$route.query && this.$route.query.res){
					var res = this.$route.query.res;
				}
				if(res){
					var obj = res.data.data[0];
				}
				
				console.log(res, '路由参数');

				if(res != null) {
					if(res.data.data[0] && res.data.data[0].couponsInfo && res.data.data[0].couponsInfo.length){
						this.couponCount = res.data.data[0].couponsInfo.length;
					}
				}
				if(res != null) {
					this.goodsList = obj.goodsList;
					this.storeOrderNo = obj.storeOrderNo;
					this.shopId = obj.shopId;
					this.getGoodsNum();
					this.goodsTotalMoney = obj.goodsTotalMoney; // 优惠活动后的金额
					//					this.goodsMoney = obj.goodsTotalMoney; // 用于计算优惠券金额
					this.goodsPromTotalMoney = obj.goodsPromTotalMoney; // 实付金额
					this.discountMoney = obj.discountMoney;
					this.couponArr = this.newCouponArr(obj.couponsInfo, 1);
					this.couponArrHtm = this.newCouponArr(obj.couponsInfo, 2);

				
					var giftArr = res.data.data[0].giftVOPresentList.concat(res.data.data[0].couponCodePresentList);
					this.getSendNameArr(giftArr);
					console.log(giftArr,'赠品信息')
					console.log('首次渲染路由 实付金额', obj.goodsPromTotalMoney);
					console.log('首次渲染页面展示 实付金额', this.goodsPromTotalMoney);
					console.log(obj.goodsTotalMoney, 'res.data goodsTotalMoney获取路由参数2');
					console.log(this.couponArr, 'res.data.data couponsInfo获取路由参数3');
					console.log(obj.discountMoney, 'res.data.data couponsInfo 获取路由参数4');
				}

				//				let params = {
				//					storeOrderNo: 0
				//				};
				//
				//				let config = {
				//					url: window.api.trade_host + '/orderOffline/getOrderGoodsInfo',
				//					method: 'GET',
				//					params,
				//					headers: {
				//						'sessionId': this.sessionId
				//					},
				//				};
				//				axios(config).then((res) => {
				//					console.log(res.data.data[0], '后台返回');
				//					if(!res.data.data[0]) {
				//						return;
				//					}
				//					this.orderData = res.data.data[0];
				//					this.goodsList = res.data.data[0].goodsList;
				//					this.goodsNum(); //计算共几件商品
				//				})
			},
			getSendNameArr(giftArr){
				 this.sendNameArr = [];
				 var arr = giftArr;
				 if(arr && arr.length){
				 	for(let i = 0; i < arr.length; i++){
//				 		console.log(arr[i],'礼包');
				 		if(arr[i] != null && arr[i].giftName){
				 			this.sendNameArr.push(arr[i].giftName);
				 		}
				 		if(arr[i] != null && arr[i].couponName){
				 			this.sendNameArr.push(arr[i].couponName);
				 		}
					}
				 }
	        },
			//过滤优惠券数组增加同组标志
			newCouponArr(arr, num) {
				var newArr = [];
				for(let i = 0; i < arr.length; i++) {
					for(let j = 0; j < arr[i].couponCodeList.length; j++) {
						arr[i].couponCodeList[j].relIndex = i;
						newArr.push(arr[i].couponCodeList[j]);
					}
				}
				if(num === 1) {
					return newArr;
				} else if(num === 2) {
					return arr;
				}

			},
			//获取优惠金额
			//			getCouponMoney(el) {

			//				let arr = this.getTicketList;
			//				console.log(arr.length);
			//				var num = 0;

			//				this.money = this.oldGoodsMoney;
			//				console.log(this.money, '总共的金额')
			//				for(let i = 0; i < arr.length; i++) {
			//					console.log(arr[i], '*****’');
			//					if(arr[i].couponType != null) {
			//						if(arr[i].couponType == 1) {
			//							num += Number(this.goodsMoney) * ((10 - Number(arr[i].couponDiscount)) / 10); //打几折
			//							console.log(num, 'ss5869ss');
			//						}
			//						if(arr[i].couponType == 2) {
			//							num += arr[i].couponAmount;
			//							console.log(arr[i].couponAmount, '100')
			//						}
			//						console.log(num, '选完券后')
			//					}
			//				}
			//				if(num == null) {
			//					num = 0;
			//				}
			//
			//				this.couponMoney = Number(num);
			//
			//			},
			changeCoupon() {
				let url = window.api.trade_host + "/orderOffline/calculatOrderPrice";
				let params = {
					storeOrderNo: this.storeOrderNo, //pos机订单编号
					shopId: this.shopId //门店编码
				};
				if(this.couponFlag != '') {
					let arr = this.getCouponParams();
					params.qrCode = arr;
				}
				let config = {
					url: url,
					method: 'POST',
					data: params,
					headers: {
						'sessionId': this.sessionId,
					},
				};

				axios(config).then((res) => {
					console.log(res.data.data[0], '选择优惠券及时计算金额');
					console.log(res.data.data[0].goodsTotalMoney, '商品总金额');
					console.log(res.data.data[0].goodsPromTotalMoney, '优惠后总金额');
					console.log(res.data.data[0].discountMoney, '优惠金额');

					this.goodsTotalMoney = res.data.data[0].goodsTotalMoney; // 商品金额
					this.discountMoney = res.data.data[0].discountMoney; // 优惠的金额
					this.goodsPromTotalMoney = res.data.data[0].goodsPromTotalMoney;
				})
			},
			goInfomation() {
				this.$router.push({
					path: 'orderInformation',
					query: {
						arr: this.goodsList
					}
				});
			},
			//	       	 展示优惠券
			showCoupon() {
				//				console.log("sss")
				this.$refs.coupon.showCover()
			},
			//获取总金额
			getGoodsNum() {
				if(this.goodsList.length != 0) {
					for(let i = 0; i < this.goodsList.length; i++) {
						if(this.goodsList[i].goodsType == 7){
							this.num += 1
						}else{
							this.num += this.goodsList[i].goodsNum;
						}
					}
				}
			},
			goBack() {
				window.history.back();
			},
			checkeParams() {

			},
			getCouponParams() {
				let arr = this.getTicketList;
				let newArr = [];
				for(let i = 0; i < arr.length; i++) {
					newArr.push(arr[i].qrCode);
				}
				let str = newArr.join();
				return str;
			},
			getCipher() {
				let url = window.api.customer_host + "/customer/getCustomer";
				let config = {
					url: url,
					method: "GET",
					headers: {
						sessionId: localStorage.getItem("sessionId")
					}
				}
				axios(config).then((res) => {
					if(res.data.returnCode) {
						console.log(res.data.data[0].walletStatus, '是否设置密码');
						this.walletStatus = res.data.data[0].walletStatus; // 0 代表暂未设置密码   1  代表已经设置密码
						this.moneyWithoutC = res.data.data[0].moneyWithoutCode; //钱包免密金额
					}

				})
			},
			showGiftCard() {
				if(this.walletStatus == 1) {
					this.$refs.giftCard.showCover();
				} else {
					MessageBox.confirm('去设置支付密码').then((action) => {
						console.log(action);
						this.$router.push('SetKeyWallet');
					})
				}

			},
			//是否使用钱包支付  
			checkBuyByCard() {
				var flag = this.getUseGiftCard;
				//      		console.log(flag);
				return flag;
			},
			//判断是否需要填密码
			checkPurse() {
				let flag = this.checkBuyByCard();
				if(flag) {
					var balanceM = Number(this.getAvailAmount); // 钱包可用余额
					var moneyWithoutC = Number(this.moneyWithoutC); // 钱包免密金额
					var totalMoney = Number(this.goodsPromTotalMoney); // 订单应付金额
					console.log(moneyWithoutC, 'en ')
					if(moneyWithoutC == null || moneyWithoutC == undefined || moneyWithoutC == 0) {
						console.log('用户没有设置免密金额，需要验证密码')
						this.$refs.pursekey.showOrHide();
						this.$refs.pursekey.clearKeyall();
						return
					}
					//1 钱包支付金额是否 大于最大免密金额   (可用余额)
					if(balanceM >= totalMoney) {
						//使用 应付金额 判断是否填写密码  订单完成 不用去支付页
						if(totalMoney > moneyWithoutC) {
							//填密码
							//	      				 	this.showMask = true;
							this.$refs.pursekey.showOrHide();
							this.$refs.pursekey.clearKeyall();
							//	      				 	this.setShowMask(true);
						} else {
							//不填密码
							console.log('不用输入密码1');
							this.toPay();
						}

					} else {

						if(balanceM > moneyWithoutC) {
							//填密码
							this.$refs.pursekey.showOrHide();
							this.$refs.pursekey.clearKeyall();
						} else {
							//不填密码
							//							console.log(this.$refs.pursekey);
							this.toPay();
							//	        			 	this.setShowMask(true);
						}
					}
				} else {
					this.toPay();
				}
			},
			toPay() {

				//防止多次点击下单
        		if(!this.clickFlag){
        			return ;
        		}
				
				this.clickFlag = false;  // 点击后置为禁用状态


				let params = {
					storeOrderNo: this.storeOrderNo, //pos机订单编号
					shopId: this.shopId //门店编码
				};
				if(this.couponFlag != '') {
					let arr = this.getCouponParams();
					params.qrCode = arr;
				}

				var flag = this.checkBuyByCard(); //入参 walletPayed 0 代表常规支付   1代表钱包支付  目前这个参数已废弃
				if(flag) {
					params.walletPayed = 1;
				} else {
					params.walletPayed = 0;
				}

				console.log(params, '请求参数');
				let config = {
					url: window.api.trade_host + '/orderOffline/createNotPayOrder',
					method: 'POST',
					data: params,
					headers: {
						'sessionId': this.sessionId,
						'Content-Type': 'application/json',
						'Accept': 'application/json'
					},
				};
				try {
					axios(config).then((res) => {
						
						this.clickFlag = true;  //接口返回  解除点击禁用
						
						console.log(res);
						console.log(res.readyState, res.status);
						console.log(res);
						console.log(res.data)
						//						console.log(res.data.data);
						if(res.status == 200) {
							console.log(res);
							if(res.data.returnCode == 1) {
								console.log('订单生成');
								var arr = [];
								var orderNo = res.data.data[0].parentOrderNo;

								this.$router.push({name: "pay", params: {orderNo:orderNo,orderType:xianxia}});
								//	commonObject.confirm_order = {'orderNo': orderNo, 'realPay': submitInfor.allPrice.replace('￥','')}
								//								var u = navigator.userAgent;

								//								var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
								//								var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
								//								if(isAndroid) {
								//									this.$router.push({name: "apay", params: {orderNo:orderNo,orderType:1}});
								//								} else if(isIOS) {
								////									this.$router.push('ipay/' + orderNo);
								//									this.$router.push({name: "ipay", params: {orderNo:orderNo,orderType:1}});
								//									//	console.log('苹果');
								//								} else {
								////									this.$router.push('apay/' + orderNo);
								//									this.$router.push({name: "apay", params: {orderNo:orderNo,orderType:1}});
								//								}

							} else {
								console.log('下单失败')
								Toast({
									message: '下单失败',
									duration: 1000,
									type: 'fail'
								});
							}
						} else {
							Toast({
								message: '生成订单失败',
								duration: 1000,
								type: 'fail'
							});
						}
					})
				} catch(err) {
					this.clickFlag = true;  //接口返回  解除点击禁用
					Toast({
						message: '生成订单失败',
						duration: 1000,
						type: 'fail'
					});
				}
			}
		},
		watch: {

		},
		beforeDestroy() {
			this.setUseGiftCard(false);
			//	    	this.setFpObj({});   // 重置发票对象的在indexvue中实现
		},
		created() {
			console.log(this.$route.query,'旧线下订单信息1');
			console.log(this.$route.query.res,'旧线下订单信息2');
			if(!this.$route.query || !this.$route.query.res){
				this.$router.push('profile');
			}else{
				this.initData();
			}
			
//			this.getCipher(); // 是否设置钱包支付密码
		}
	}
</script>

<style scoped="scoped">
	.settle_accounts {
		height: 3rem;
		background: rgba(255, 255, 255, 0.9);
		overflow: hidden;
		position: fixed;
		width: 100%;
		left: 0;
		bottom: -1px;
		display: table;
		border-top: 1px solid #eaeaea;
		z-index: 1;
	}
	
	.scroller_list {
		overflow-y: auto;
	}
	
	.iscroll_list {
		height: 5.5rem !important;
	}
	
	.scroller_list {
		position: relative;
	}
	
	.vue_app {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}
	
	.content {
		flex: 1;
		overflow-y: auto;
		width: 100%;
	}
	.choose_list .statistics{
		padding-top: 1.9rem;
	}
</style>